<template>
  <div class="container">
    <el-card class="tree-card">
      <template #header>
        <div class="card-header">
          <el-icon><Folder /></el-icon>
          <span>Department Tree</span>
        </div>
      </template>

      <!-- Tree Search -->
      <div class="tree-search">
        <el-input
            v-model="treeFilterText"
            placeholder="Filter departments"
            clearable
            @input="filterTree"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- Tree with Add/Delete buttons -->
      <div class="tree-container">
        <el-tree
            ref="treeRef"
            class="filter-list"
            :data="filteredTreeData"
            :props="treeProps"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
        >
          <template #default="{ node, data }">
            <span class="tree-node">
              <el-icon v-if="node.isLeaf"><Document /></el-icon>
              <el-icon v-else><Folder /></el-icon>
              <span>{{ node.label }}</span>
              <span v-if="false" class="tree-actions">
                <el-button
                    size="small"
                    type="text"
                    @click.stop="handleAddNode(data)"
                >
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button
                    size="small"
                    type="text"
                    @click.stop="handleDeleteNode(data)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>User List</span>
        </div>
      </template>

      <!-- Query Conditions -->
      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="Name">
            <el-input
                v-model="queryParams.name"
                placeholder="Name"
                clearable
            />
          </el-form-item>
          <el-form-item label="Status">
            <el-select
                v-model="queryParams.status"
                placeholder="Status"
                clearable
            >
              <el-option label="Active" value="1" />
              <el-option label="Inactive" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">Search</el-button>
            <el-button @click="resetQuery">Reset</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- Table with Toolbar -->
      <div class="table-toolbar">
        <el-button type="primary" @click="handleAddUser">
          <el-icon><Plus /></el-icon>
          Add User
        </el-button>
        <el-button
            type="danger"
            :disabled="!selectedUsers.length"
            @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          Delete
        </el-button>
      </div>

      <!-- User Table -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" width="120" />
        <el-table-column prop="department" label="Department" width="150" />
        <el-table-column prop="email" label="Email" width="180" />
        <el-table-column prop="status" label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="Create Time" width="180" />
        <el-table-column label="Operations" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">Edit</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
            >Delete</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  Folder,
  Document,
  Search,
  Plus,
  Delete,
  List
} from '@element-plus/icons-vue'

// Tree Data
interface TreeNode {
  id: string
  label: string
  children?: TreeNode[]
}

const treeRef = ref()
const treeFilterText = ref('')
const filteredTreeData = ref<TreeNode[]>([])
const currentDepartment = ref('')

// Original tree data
const treeData: TreeNode[] = [
  {
    id: '1',
    label: 'Headquarters',
    children: [
      {
        id: '1-1',
        label: 'R&D',
        children: [
          { id: '1-1-1', label: 'Frontend' },
          { id: '1-1-2', label: 'Backend' }
        ]
      },
      {
        id: '1-2',
        label: 'Marketing',
        children: [
          { id: '1-2-1', label: 'Design' },
          { id: '1-2-2', label: 'Promotion' }
        ]
      }
    ]
  },
  {
    id: '2',
    label: 'Branch Office',
    children: [
      {
        id: '2-1',
        label: 'Sales',
        children: [
          { id: '2-1-1', label: 'Domestic' },
          { id: '2-1-2', label: 'International' }
        ]
      }
    ]
  }
]

// Table Data
interface UserItem {
  id: number
  name: string
  department: string
  email: string
  status: string
  createTime: string
}

const queryParams = ref({
  name: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const tableData = ref<UserItem[]>([])
const total = ref(0)
const loading = ref(false)
const selectedUsers = ref<UserItem[]>([])

// Tree Methods
const treeProps = {
  children: 'children',
  label: 'label'
}

const filterTree = () => {
  treeRef.value?.filter(treeFilterText.value)
}

const filterNode = (value: string, data: TreeNode) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

const handleNodeClick = (data: TreeNode) => {
  currentDepartment.value = data.label
  handleQuery() // Refresh table when department changes
}

const handleAddNode = (data: TreeNode) => {
  console.log('Add node under:', data.label)
  // Implement your add node logic
}

const handleDeleteNode = (data: TreeNode) => {
  console.log('Delete node:', data.label)
  // Implement your delete node logic
}

// Table Methods
const fetchTableData = async () => {
  loading.value = true
  try {
    // Mock API call
    await new Promise(resolve => setTimeout(resolve, 500))

    // Mock data
    const mockData: UserItem[] = Array.from({ length: 50 }, (_, i) => ({
      id: i + 1,
      name: `User ${i + 1}`,
      department: currentDepartment.value || 'Headquarters',
      email: `user${i + 1}@example.com`,
      status: Math.random() > 0.5 ? '1' : '0',
      createTime: new Date().toLocaleDateString()
    }))

    // Filter data
    let filteredData = mockData.filter(
        user =>
            (!queryParams.value.name || user.name.includes(queryParams.value.name)) &&
            (!queryParams.value.status || user.status === queryParams.value.status) &&
            (!currentDepartment.value || user.department === currentDepartment.value)
    )

    total.value = filteredData.length
    const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize
    tableData.value = filteredData.slice(start, start + queryParams.value.pageSize)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  fetchTableData()
}

const resetQuery = () => {
  queryParams.value = { name: '', status: '', pageNum: 1, pageSize: 10 }
  fetchTableData()
}

const handleSelectionChange = (val: UserItem[]) => {
  selectedUsers.value = val
}

const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  fetchTableData()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  fetchTableData()
}

const handleAddUser = () => {
  console.log('Add user')
  // Implement your add user logic
}

const handleEdit = (row: UserItem) => {
  console.log('Edit user:', row)
  // Implement your edit logic
}

const handleDelete = (row: UserItem) => {
  console.log('Delete user:', row)
  // Implement your delete logic
}

const handleBatchDelete = () => {
  console.log('Batch delete:', selectedUsers.value)
  // Implement your batch delete logic
}

// Initialize
onMounted(() => {
  filteredTreeData.value = JSON.parse(JSON.stringify(treeData))
  fetchTableData()
})
</script>

<style scoped>
.container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.tree-card {
  width: 300px;
  flex-shrink: 0;
}

.table-card {
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.tree-search {
  margin-bottom: 16px;
}

.tree-container {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.tree-actions {
  margin-left: auto;
  visibility: hidden;
}

:deep(.el-tree-node__content:hover) .tree-actions {
  visibility: visible;
}

.query-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-border-color: #eaeaea;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: #f5f7fa;
}
</style>